// src/components/core/Search.tsx
import { Button, Col, Divider, Form, Input, Row, Select } from 'antd'
import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getCategory } from '../../store/actions/category.action'
import { AppState } from '../../store/reducers/index'
import { CategoryState } from '../../store/reducers/category.reducer'
import ProductItem from './ProductItem'
import { searchProduct } from '../../store/actions/product.action'
import { ProductState } from '../../store/reducers/product.reducer'

const Search = () => {

    const dispatch = useDispatch()

    // 获取商品分类列表
    const {category} = useSelector<AppState, CategoryState>(state => state.category)

    // 获取搜索商品数据
    const {search} = useSelector<AppState, ProductState>(state => state.product)

    useEffect(() => {
        dispatch(getCategory())
    }, [])

    // 筛选商品
    const onFinish = (value: {category: string; search: string}) => {
        dispatch(searchProduct({category: value.category, search: value.search}))
    }
    return (
    <>
        {/* layout="inline" 横向布局 */}
        <Form layout="inline" initialValues={{ category: 'All'}} onFinish={onFinish}>
            {/* Input.Group 分组 */}
            <Input.Group compact>
                <Form.Item name="category">
                    <Select>
                    {
                        category.result.map(item => (
                            <Select.Option key={item._id} value={item._id}>{item.name}</Select.Option>
                        ))
                    }
                    </Select>
                </Form.Item>
                <Form.Item name="search">
                    <Input placeholder="请输入搜索关键字" />
                </Form.Item>
                <Form.Item>
                    <Button htmlType="submit">搜索</Button>
                </Form.Item>
            </Input.Group>
        </Form>
        <Divider />
        {/* gutter 间距 */}
        <Row gutter={[16, 16]}>
        {
            // 显示搜索商品
            search.map(item => (
                <Col span="6" key={item._id}>
                    <ProductItem product={item} />
                </Col>
            ))
        }
        </Row>
    </>
    )
}

export default Search